JavaScript Recipes by Russ Ferguson & Keith Cirkel

JavaScript Recipes by Russ Ferguson & Keith Cirkel
Author: Russ Ferguson & Keith Cirkel
Language: eng
Format: epub
Publisher: Apress, Berkeley, CA

Multiplying by Powers of 2 with the Left Shift (<<) Operator


Problem


You want to take a signed 32-bit integer (that is, a whole number with a maximum value of 2,147,483,647 and a minimum value of -2,147,483,647) and multiply it by a power of two.

Solution


Bitwise shift operators are useful for doing low-level binary computation, especially on numbers (although they convert them to 32-bit signed integers). The left shift bitwise operator can be used to shift binary bits to the left, which allows you to multiply a 32-bit integer by a power of 2.